package com.LeeCode;

import java.util.TreeMap;

/**
 * 绝对差不超过限制的最长连续子数组
 */

public class Code1438 {
    public static void main(String[] args) {
        int[] nums = {4, 2, 2, 2, 4, 4, 2, 2};
        int limit = 0;
        System.out.println(new Code1438().longestSubarray(nums, limit));
    }

    public int longestSubarray(int[] nums, int limit) {
        int ans = 0, left = 0;
        TreeMap<Integer, Integer> map = new TreeMap<>();

        for (int right = 0; right < nums.length; right++) {
            map.merge(nums[right], 1, Integer::sum);
            while (map.lastKey() - map.firstKey() > limit) {
                map.merge(nums[left], -1, (old, delta) -> {
                    int res = old + delta;
                    return res > 0 ? res : null;
                });
                left++;
            }

            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}
